/*
 * Copyright 2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.chart.services

import com.google.zxing.Result
import com.google.zxing.client.result.ResultParser
import org.seppiko.chart.exceptions.SeppikoProcessorException
import org.seppiko.chart.models.ServiceEntity
import org.seppiko.chart.utils.ImageUtil
import org.seppiko.chart.utils.JsonUtil
import org.seppiko.commons.utils.ObjectUtil
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import java.io.InputStream
import java.util.ArrayList

/**
 *
 * @author Leonard Woo
 */
@Service
class DecodeService {

  @Throws(SeppikoProcessorException::class)
  fun decodeCHX(input: InputStream): ServiceEntity {
    val se = ServiceEntity()
    se.type = MediaType.APPLICATION_JSON

    val image = ImageUtil.processStream(input)
    if (ObjectUtil.isNull(image)) {
      throw SeppikoProcessorException(400, "barcode decode failed.")
    }
    image?.flush()
    val json = LinkedHashMap<String, Any>()
    val results: ArrayList<Result>? = image?.let { ImageUtil.processImage(it) }

    if (results == null || results.isEmpty()) {
      throw SeppikoProcessorException(404, "Cannot found any barcode.")
    }

    results.forEach { result: Result? ->
      run {
        if (result != null) {
          json["status"] = 200
          json["rawtext"] = result.text
          json["rawbytes"] = result.rawBytes
          json["format"] = result.barcodeFormat.name
          json["parsedresult"] = ResultParser.parseResult(result).displayResult
        }
      }
    }
    se.data = JsonUtil.toJson(json).toByteArray()

//    image?.close()
    return se
  }
}